import 'plugins/toggle-disabled';
import 'plugins/serialize-object';
import 'plugins/fill-form';
import { del, get, put } from 'utils/request';
import { is_obj_lte, getParamFromSearch, getUser } from 'utils';
import E from 'wangeditor';
import 'utils/twitter-bootstrap-hover-dropdown';

// 定义表单相关变量
const id = getParamFromSearch().id;
const $form = $('#myForm');
let savedData = {}; // 已保存的简历数据
const $submit = $form.find('.submit').toggleDisabled(true);
const $preview = $form.find('.preview').toggleDisabled(true);

// 个人优势富文本编辑器
const advEditor = new E("#advantage");
advEditor.config.height = 200;
advEditor.config.menus = ['list'];
advEditor.config.placeholder = '例如：两年UI设计经验，熟悉IOS和Android的界面设计规范，对产品本色有独特见解，有一定的手绘基础';
advEditor.create();

// 获取简历数据
if (id) { // 指定了简历id，则意味着修改简历，先获取该简历数据再显示表单
  get(`resume/resumes/${id}`).done(d => {
    savedData = d || {};
    $preview.toggleDisabled(false);
    $form.fillForm(savedData);
    advEditor.txt.html(d.advantage);
    $('body').show();
  });
} else { // 未指定简历id，则意味着要新建简历，直接显示表单
  alert('链接有误，请检查');
}

// 开启表单验证
$form.validator({ disable: false });

// 保存简历
$form.on('submit', function (e) {
  if (e.isDefaultPrevented()) {
    console.log('表单验证不通过');
  } else {
    console.log('表单验证通过');
    e.preventDefault();
    let formData = $form.serializeObject();
    formData.advantage = advEditor.txt.html();
    put('resume/resumes/' + id, formData).done(d => {
      alert('保存成功');
      savedData = d || {};
      $submit.toggleDisabled(true);
    });
  }
});

// 监听表单内容变化
$form.on('change', function (e) {
  let formData = $form.serializeObject();
  formData.advantage = advEditor.txt.html();
  $submit.toggleDisabled(is_obj_lte(formData, savedData));
});

// 监听advEditor内容变化
advEditor.config.onchange = function (newHtml) {
  let formData = $form.serializeObject();
  formData.advantage = newHtml;
  $submit.toggleDisabled(is_obj_lte(formData, savedData));
};

// 点击删除简历
$form.on('click', '.del', function (e) {
  if (!confirm('确定要删除吗？')) return;
  del('resume/resumes/' + id).done(d => {
    alert(d);
    location.replace('resumes.html?uid=' + getUser().id);
  })
});

// 点击预览简历
$form.on('click', '.preview', function (e) {
  location.href = 'resume-view.html?id=' + id;
});